/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.analyze.preview;

import cn.ac.nercis.pes.community.component.controls.MenuListCell;
import cn.ac.nercis.pes.community.component.dialog.MessageDialog;
import cn.ac.nercis.pes.community.component.dialog.MessageType;
import cn.ac.nercis.pes.community.component.spreadsheet.analyze.preview.OverallEvalPreviewSheetView;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.evaluation.ResultCorrectionViewMapper;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.model.vo.evaluation.ResultCorrectionVO;
import cn.ac.nercis.pes.community.utils.AppUtils;
import cn.ac.nercis.pes.community.utils.ControlUtils;
import cn.ac.nercis.pes.community.utils.LogUtils;
import cn.ac.nercis.pes.community.utils.SpringUtils;
import cn.ac.nercis.pes.model.dto.evaluation.analyze.ResultCorrectionDTO;
import cn.ac.nercis.pes.service.evaluation.ResultCorrectionService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * 整体测评预览控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class OverallEvalPreviewController implements Initializable {
    protected final static Integer MAX_SHOW_MENU_TEXT_LENGTH = 10;

    @FXML
    private ListView<MenuVO> menuListView;

    @FXML
    private OverallEvalPreviewSheetView sheetView;

    private final ResultCorrectionService resultCorrectionService;
    private final ExecutorService executor;

    private String currentSystemId;
    private MenuVO currentLayerTarget;
    private MenuVO currentUnitTarget;
    private StackPane page;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);

    public OverallEvalPreviewController() {
        this.resultCorrectionService = SpringUtils.getBean(ResultCorrectionService.class);
        this.executor = SpringUtils.getBean(ExecutorService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        this.initializeControl();
        realTimeSaveManager.listenerSheetChange(this.sheetView);
    }

    public void initializeData(String systemId, MenuVO layerTarget, StackPane page) {
        LogUtils.info(log, "初始化整体测评预览内容...");
        this.currentSystemId = systemId;
        this.currentLayerTarget = layerTarget;
        this.page = page;
        loadMenuData();
    }

    private void initializeControl() {
        menuListView.setCellFactory(cf -> new MenuListCell(MAX_SHOW_MENU_TEXT_LENGTH, false));
        menuListView.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (Objects.nonNull(newValue)) {
                        loadCorrection(newValue);
                    }
                });
    }

    public void realTimeSave() {
        LogUtils.info(log, "执行即时保存操作...");
        batchSaveCorrection();
    }

    private void batchSaveCorrection() {
        List<ResultCorrectionDTO> resultCorrectionDTOS = this.sheetView.getModifyData().stream()
                .filter(ResultCorrectionVO::isChange)
                .map(ResultCorrectionViewMapper.INSTANCE::toDTO)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(resultCorrectionDTOS)) {
            return;
        }
        LogUtils.info(log, "批量保存测评对象结果修正信息...");
        LogUtils.record(log, "请求数据:{}", resultCorrectionDTOS);
        //未保存的数据进行批量保存
        CompletableFuture.supplyAsync(() -> this.resultCorrectionService.batchSaveResultCorrection(resultCorrectionDTOS), this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (!res.isSuccess()) {
                        AppUtils.showMessageDialog(res.getMsg(), MessageType.FAIL, this.page);
                    } else {
                        queryCorrectionList(currentUnitTarget);
                        ControlUtils.refreshScoreInfo(this.currentSystemId);
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("批量保存测评对象结果修正信息出错!", ex);
                    return null;
                });
    }

    private void loadMenuData() {
        menuListView.getItems().clear();
        LogUtils.info(log, "获取单元指标信息...");
        LogUtils.record(log, "请求数据，systemId：{},targetId:{}", this.currentSystemId, currentLayerTarget.getCode());
        CompletableFuture.supplyAsync(() -> resultCorrectionService.findUnitTargetByLayerTarget(this.currentSystemId,
                        currentLayerTarget.getCode()), this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        res.getData().forEach(ute -> menuListView.getItems().add(new MenuVO(2, ute.getUnitTargetId(),
                                ute.getUnitTargetName(), ControlUtils.finishStateToIcon(ute.getFinishState()))));
                        selectedDefaultMenu();
                    } else {
                        this.sheetView.loadContent(Collections.emptyList());
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("获取单元指标信息出错!", ex);
                    return null;
                });
    }

    private void loadCorrection(MenuVO unitTargetEval){
        currentUnitTarget = unitTargetEval;
        this.queryCorrectionList(unitTargetEval);
    }

    private void queryCorrectionList(MenuVO currentUnitTarget) {
        LogUtils.info(log, "获取整体测评预览内容...");
        LogUtils.record(log, "请求数据，systemId：{},targetId:{}", this.currentSystemId, currentUnitTarget.getCode());
        CompletableFuture.supplyAsync(() -> this.resultCorrectionService.findResultCorrections(this.currentSystemId,
                        currentUnitTarget.getCode(), true),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    this.sheetView.loadContent(res.stream()
                            .map(ResultCorrectionViewMapper.INSTANCE::toVO)
                            .toList());
                }))
                .exceptionally((ex) -> {
                    log.error("获取整体测评预览内容出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL).withMessage("加载数据表内容失败！")
                            .build().show();
                    return null;
                });
    }

    private void selectedDefaultMenu(){
        boolean isSelected = false;
        for(MenuVO menuObj : menuListView.getItems()){
            isSelected = selectedDefaultMenu(menuObj,menuListView);
            if(isSelected){
                break;
            }
        }
        if(!isSelected){
            menuListView.getSelectionModel().select(0);
        }
    }

    private boolean selectedDefaultMenu(MenuVO menuLabel,ListView<MenuVO> menu){
        if(Objects.isNull(menuLabel) || StringUtils.equals(menuLabel.getIcon(),"finish-process-icon")){
            return false;
        }
        menu.getSelectionModel().select(menuLabel);
        return true;
    }

}